package controller;

import pojo.User;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/web")
public class TestController {

    @InitBinder
    public void initBinder(WebDataBinder binder)
    {
        // 注册自定义的属性编辑器
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    }
    @RequestMapping("/testDate")
    public String processForm(@RequestParam("date") Date date)
    {
        // 处理请求，使用绑定后的数据
        System.out.println("Received date: " + date);
        return "result";
    }

    @RequestMapping("/index")
    public String hello() {
        return "index";
    }

    @RequestMapping("*/index")
    public String mapping1() {

        return "testA";
    }

    @RequestMapping("/inde?")//匹配 /web/index、/web/indea，...
    public String mapping2() {

        return "testB";
    }

    //    匹配：/web/del、/web/save、/web/queryList
    @RequestMapping({"/{[queryList|del|save}"})
    public String mapping3(){

        return "正则表达式匹配";
    }

    @RequestMapping("/t2")
    public void test2(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
        rsp.sendRedirect("/index.jsp");
    }
    @RequestMapping("/t3")
    public void test3(HttpServletRequest req, HttpServletResponse rsp) throws Exception {
        //转发
        req.setAttribute("msg","/t3");
        req.getRequestDispatcher("/WEB-INF/jsp/testC.jsp").forward(req,rsp);
    }


    @GetMapping("/getHeader")
    public void getUserAgent(@RequestHeader("User-Agent") String userAgent) {
        System.out.println("User Agent: " + userAgent);
    }

    @GetMapping("/{id}")
    public void testPathVariable(@PathVariable Integer id){
        System.out.println("id = "+id);
    }

    @GetMapping("/getParam")
    public void testGetParam(@RequestParam(value = "id", required = false, defaultValue = "0") Integer id){
        System.out.println("id = "+id);
    }
    
    @PostMapping("/testModelAttribute")
    public String testModelAttribute(@ModelAttribute User user){
        System.out.println(user);
        return "success";
    }


}
